package com.zuosh.service;

import com.zuosh.common.ResponseCode;
import com.zuosh.common.Result;
import com.zuosh.dao.UserPostMapper;
import com.zuosh.domain.UserPost;
import com.zuosh.domain.UserPostExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by zuoshuai on 2017/3/17.
 */
@Service
public class PostServiceImpl implements PostService {
    @Autowired
    private UserPostMapper userPostMapper;

    /**
     * 获取贴子列表
     *
     * @param example
     * @return
     */
    @Override
    public Result<List<UserPost>> listPosts(UserPostExample example) {
        Result<List<UserPost>> result = new Result<>();
        if (example == null) {
            return result.setResult(ResponseCode.PARAMETER_ERROR, null, "参数为空");
        }
        List<UserPost> userPosts = userPostMapper.selectByExample(example);
        return result.setResult(ResponseCode.SUCCESS, userPosts, "ok");
    }

    /**
     * 新增帖子
     *
     * @param userPost
     * @return
     */
    @Override
    public Result<Long> addPost(UserPost userPost) {
        Result<Long> result = new Result<>();
        if (userPost == null) {
            return result.setResult(ResponseCode.PARAMETER_ERROR, null, "parameter error");
        }
        //set time
        userPost.setGmtModify(new Date());
        userPost.setGmtCreate(new Date());
        userPostMapper.insertSelective(userPost);
//        int i = 1 / 0;
        return result.setResult(ResponseCode.SUCCESS, userPost.getId(), "ok");
    }

    /**
     * 删除帖子
     *
     * @param userPost
     * @return
     */
    @Override
    public Result<Boolean> deletePost(UserPost userPost) {
        Result<Boolean> result = new Result<>();
        if (userPost == null) {
            return result.setResult(ResponseCode.PARAMETER_ERROR, false, "parameter error");
        }
        if (userPost.getId() == null) {
            return result.setResult(ResponseCode.PARAMETER_ERROR, false, "id can not be null");
        }
        UserPostExample example = new UserPostExample();
        example.createCriteria().andIdEqualTo(userPost.getId());
        userPostMapper.deleteByExample(example);
        return result.setResult(ResponseCode.SUCCESS, true, "ok");
    }
}

